package org.bling.star.client.connect;

import org.bling.star.common.command.systems.CloseCommand;
import org.bling.star.common.connect.AbstractConnectClient;
import org.bling.star.common.connect.ConnectStatus;
import org.bling.star.common.response.BaseResponse;
import io.netty.channel.*;
import io.netty.util.concurrent.EventExecutor;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.ExecutionException;

@Slf4j
public class ClientConnection extends AbstractConnectClient {
    private EventExecutor eventExecutor;
    private Channel channel;
    private ConnectStatus status;

    public ClientConnection(Channel channel) {
        this.channel = channel;
        this.status = ConnectStatus.INIT;
        this.eventExecutor = channel.eventLoop();
    }
    public BaseResponse send(Object message) {
        Promise<BaseResponse> baseResponsePromise = (Promise<BaseResponse>) send0(message);
        BaseResponse now = null;
        try {
            now = baseResponsePromise.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return now;
    }

    @Override
    public ChannelFuture sendFuture(Object msg) {
        return null;
    }

    @Override
    public Channel channel() {
        return channel;
    }

    public boolean close() {
        this.status = ConnectStatus.SHUTDOWN;
        ChannelFuture future = channel.writeAndFlush(new CloseCommand());
        try {
            ChannelFuture close = channel.close().sync();
            if(close.isSuccess()) {
                eventExecutor.shutdownGracefully();
                channel = null;
                eventExecutor = null;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public ConnectStatus status() {
        return this.status;
    }

    @Override
    public void alive() {
        this.status = ConnectStatus.CONNECTED;
    }

}
